//
//  LLActionViewController.swift
//  LiLi
//
//  Created by liuzhu on 2019/1/5.
//  Copyright © 2019 liuzhu. All rights reserved.
//

import UIKit
let LLActionListIdentifier = "LLActionListIdentifier"
class LLActionViewController: LLBaseViewController ,UITextFieldDelegate{

    public var actions:[LLAction]?{
        didSet{
            DispatchQueue.main.async {
                 self.tableView.reloadData()
            }
        }
    }
    
    var dataPicker:EWDatePickerViewController = EWDatePickerViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(listenActionAdd), name: NSNotification.Name(rawValue: LLActionAddKey), object: nil)
        self.view.addSubview(tagSegment)
        self.view.addSubview(tableView)
        self.tagSegment.addTarget(self, action: #selector(segmentSelect(sender:)), for: UIControl.Event.valueChanged)
        tableView.register(LLActionCell.self, forCellReuseIdentifier: LLActionListIdentifier)//注册cell
    }
    
    override func viewDidAppear(_ animated: Bool) {
        loadData(tag: 0)
    }
    override func viewWillAppear(_ animated: Bool) {
        self.tabBarController?.tabBar.isHidden = false
    }
    
    @objc func listenActionAdd(){
        loadData(tag: 0)
    }

    private lazy var tableView:UITableView = {
       let t = UITableView.init(frame:CGRect(x: 0, y: tagSegment.frame.origin.y + 30, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - 135))
        t.delegate = self
        t.dataSource = self
        t.separatorStyle = .none
        return t
    }()
    
    public lazy var tagSegment:UISegmentedControl = {
        var y = CGFloat(64)
        if LLConst.getPhoneType() == PhoneType.PHONE_MAX_XR || LLConst.getPhoneType() == PhoneType.PHONE_X{
            y = 88
        }
        let sg = UISegmentedControl.init(items: ["全部","个人","工作","其他"])
        sg.frame =  CGRect(x: -5, y: y, width: UIScreen.main.bounds.size.width+10, height: 30)
        sg.tintColor = UIColor.init(red: 80/255.0, green: 80/255.0, blue: 80/255.0, alpha: 1)
        sg.selectedSegmentIndex = 0
        return sg
    }()
    
    func loadData(tag:Int) {
        if tag == 0 {
            LLActionManager.shareActionManager().queryActions(finish: { (models, isSuccess) in
                
                if models != nil{
                    if self.tagSegment.selectedSegmentIndex == 0{
                        self.actions = models
                    }else if(self.tagSegment.selectedSegmentIndex == 1){
                        var newModles = [LLAction]()
                        for model in models!{
                            if model.actionType == ActionType.ACTION_TYPE_SELF{
                                newModles.append(model)
                            }
                        }
                        self.actions = newModles
                    }else if(self.tagSegment.selectedSegmentIndex == 2){
                        var newModles = [LLAction]()
                        for model in models!{
                            if model.actionType == ActionType.ACTION_TYPE_COMPANY{
                                newModles.append(model)
                            }
                        }
                        self.actions = newModles
                    }else if(self.tagSegment.selectedSegmentIndex == 3){
                        var newModles = [LLAction]()
                        for model in models!{
                            if model.actionType == ActionType.ACTION_TYPE_OTHER{
                                newModles.append(model)
                            }
                        }
                        self.actions = newModles
                    }
                }else{
                    self.actions = [LLAction]()
                }
            })
        }
    }
    
    @objc func segmentSelect(sender:UISegmentedControl){
        loadData(tag:0)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension LLActionViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let count = self.actions?.count ?? 0
        return count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: LLActionListIdentifier, for: indexPath) as! LLActionCell
        let action = actions![indexPath.row]
        cell.action = action
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 73
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let action = actions![indexPath.row]
        let alertVC = UIAlertController.init(title: nil, message: nil
            , preferredStyle: UIAlertController.Style.actionSheet)
        let actionRemark = UIAlertAction.init(title: "日记", style: UIAlertAction.Style.default) { (_) in
            let vc = LLRemarkViewController()
            vc.action = action
            self.navigationController?.pushViewController(vc, animated: false)
        }
        let actionSet = UIAlertAction.init(title: "设置 ", style: UIAlertAction.Style.default) { (_) in
            
            self.dataPicker.dateStyle = DatePickerStyle.DATEPICKERSTYLE_ACTIONSET
            self.dataPicker.actionSetView.nameContentTF.delegate = self
            self.dataPicker.actionSetView.desContentTF.delegate = self
            self.dataPicker.actionSetView.nameContentTF.text = action.titleName
            self.dataPicker.actionSetView.desContentTF.text = action.des
            self.dataPicker.backActionInfo = { [weak self] name,des,type,repeatTag,dic in
                action.titleName = name
                action.des = des
                action.refreshTag = action.refreshTag! + 1
                LLManager.shareLLManager().saveAction(action: action, finish: { (isSuccess) in
                    if isSuccess{
                        self?.loadData(tag: 0)
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: LLActionUpdateKey), object: nil, userInfo: ["action":action])
                    }
                })
            }
            self.dataPicker.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
            /// 弹出时日期滚动到当前日期效果
            self.present(self.dataPicker, animated: true) {
            }
        }
        let actionDelete = UIAlertAction.init(title: "删除", style: UIAlertAction.Style.default) { (_) in
            let alertVC = UIAlertController(title: "提示", message: "你确定邵删除日程[\(action.titleName ?? "")]么", preferredStyle: UIAlertController.Style.alert)
            let actionSure = UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: { (_) in
                let action = self.actions![indexPath.row]
                LLActionManager.shareActionManager().deleteAction(action: action, finish: { (_isSuccess) in
                    
                    self.loadData(tag: 0)
                })
            })
            let actionCancel = UIAlertAction(title: "取消 ", style: UIAlertAction.Style.cancel, handler: { (_) in
                
            })
            alertVC.addAction(actionSure)
            alertVC.addAction(actionCancel)
            self.present(alertVC, animated: true, completion: nil)
        }
        let actionCancel = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (_) in
            
        }

        alertVC.addAction(actionRemark)
        alertVC.addAction(actionSet)
        alertVC.addAction(actionDelete)
        alertVC.addAction(actionCancel)
        present(alertVC, animated: true, completion: nil)
    }
    
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        animateViewMoving(up: true, moveValue: 200)
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        animateViewMoving(up: false, moveValue: 200)
    }
    
    func animateViewMoving (up:Bool, moveValue :CGFloat){
        let movementDuration:TimeInterval = 0.3
        let movement:CGFloat = ( up ? -moveValue : moveValue)
        UIView.beginAnimations( "animateView", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(movementDuration )
        self.dataPicker.view.frame = self.dataPicker.view.frame.offsetBy(dx: 0,  dy: movement)
        UIView.commitAnimations()
    }
}
